package com.ying.timed.service.impl;

import com.ying.timed.common.TimedEnum;
import com.ying.timed.config.CronTaskRegistrar;
import com.ying.timed.config.SchedulingRunnable;
import com.ying.timed.dao.TimedDao;
import com.ying.timed.entity.Timed;
import com.ying.timed.entity.TimedQuery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Service
public class TimedRunnerServiceImpl implements CommandLineRunner {

    private static final Logger logger = LoggerFactory.getLogger(TimedRunnerServiceImpl.class);

    @Autowired
    private TimedDao timedDao;
    @Autowired
    private CronTaskRegistrar cronTaskRegistrar;

    @Override
    public void run(String... args) {
        // 初始加载数据库里状态为正常的定时任务
        TimedQuery timedQuery = new TimedQuery();
        timedQuery.createCriteria().andJobStatusEqualTo(TimedEnum.NORMAL.getIndex());
        List<Timed> timedList = timedDao.selectByQuery(timedQuery);
        if (!CollectionUtils.isEmpty(timedList)) {
            for (Timed timed : timedList) {
                SchedulingRunnable task = new SchedulingRunnable(timed.getBeanName(), timed.getMethodName(), timed.getMethodParams());
                cronTaskRegistrar.addCronTask(task, timed.getCronExpression());
            }
            logger.info("定时任务已加载完毕...");
        }
    }
}